package org.ats.mail;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Service;

@Service("AtsMailSender")
public class AtsMailSender implements Callable<Boolean>/*, ApplicationContextAware */{
	
	@Autowired
	private ApplicationContext context;

	@Autowired
	private JavaMailSenderImpl javaMailSenderImpl;
	
	private MailTemplates mailTemp;
	private List<String> mailToList;
	private File attachment;
	
	public ApplicationContext getContext() {
		return context;
	}

	public void setContext(ApplicationContext context) {
		this.context = context;
	}
	
	
	public JavaMailSenderImpl getJavaMailSenderImpl() {
		return javaMailSenderImpl;
	}

	public void setJavaMailSenderImpl(JavaMailSenderImpl javaMailSenderImpl) {
		this.javaMailSenderImpl = javaMailSenderImpl;
	}

	public synchronized MailTemplates getMailTemp() {
		return mailTemp;
	}

	public synchronized void setMailTemp(MailTemplates mailTemp) {
		this.mailTemp = mailTemp;
	}

	public synchronized List<String> getMailToList() {
		return mailToList;
	}

	public synchronized void setMailToList(List<String> mailToList) {
		this.mailToList = mailToList;
	}

	public synchronized File getAttachment() {
		return attachment;
	}

	public synchronized void setAttachment(File attachment) {
		this.attachment = attachment;
	}

	public void sendMsg(MimeMessage msg) throws MailException {
		
		System.out.println("start time: " + new Date(System.currentTimeMillis()).toString());
		getJavaMailSenderImpl().send(msg);
		System.out.println( "end time: " + new Date(System.currentTimeMillis()).toString());
		try {
			System.out.println("Sending Date********" + msg.getSentDate().toString());
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	

	public Boolean call() {
		AtsMailPreperator atsMailPrepatrator;
		try {
			atsMailPrepatrator = (AtsMailPreperator) getContext().getBean("AtsMailPreperator");
			atsMailPrepatrator.PrepareMIMEMsg(getMailTemp(), getMailToList(), getAttachment());
			sendMsg(atsMailPrepatrator.getMime());
			return true;
		} catch (MailException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
		
	}

}
